<template>
  <div class="out">
    <zHeader pageTitle="AI问答"></zHeader>
    
    <div class="pageOut">
      <div class="chatContentArea" ref="chatContentArea" @touchstart="chatContentAreaTouchStartHandler">
        <div class="chatItemArea" v-for="(item, index) in AIchatData" :key="index">
          <div class="AIArea" v-if="item.type == 'AI'">
            <div class="iconArea">
              <svg class="AIAvatarIcon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 32 32" width="40" height="40" style="" filter="none">
                <g>
                <path d="M25.792 12.544h-0.736v-1.024c0-1.664-1.376-2.976-3.040-2.976h-4.928v-2.496c0.654-0.374 1.088-1.068 1.088-1.864 0-0.009-0-0.017-0-0.026v0.001c0-1.184-0.96-2.176-2.176-2.176s-2.176 0.992-2.176 2.176c0 0.832 0.448 1.504 1.088 1.888v2.464h-4.928c-0.001 0-0.002 0-0.003 0-1.66 0-3.005 1.345-3.005 3.005 0 0.001 0 0.002 0 0.003v-0 1.024h-0.768c-0.928 0-1.696 0.768-1.696 1.728v3.648c0 0.928 0.768 1.696 1.696 1.696h0.768v1.056c0 1.664 1.344 2.976 3.008 2.976h1.408v1.6c0 0.928 0.768 1.696 1.696 1.696h5.824c0.928 0 1.696-0.768 1.696-1.696v-1.6h1.408c1.664 0 3.040-1.312 3.040-2.976v-1.056h0.736c0.928 0 1.696-0.768 1.696-1.696v-3.648c0-0.928-0.768-1.728-1.696-1.728zM9.408 13.696c0-1.088 0.896-1.984 1.984-1.984s1.984 0.896 1.984 1.984-0.896 1.984-1.984 1.984c-0.003 0-0.007 0-0.011 0-1.090 0-1.973-0.883-1.973-1.973 0-0.004 0-0.008 0-0.012v0.001zM18.72 20.96h-5.44c-0.896 0-1.6-0.736-1.6-1.632s0.704-1.632 1.6-1.632h5.44c0.896 0 1.632 0.736 1.632 1.632s-0.736 1.632-1.632 1.632zM20.608 15.68c-0.003 0-0.007 0-0.011 0-1.090 0-1.973-0.883-1.973-1.973 0-0.004 0-0.008 0-0.012v0.001c0-1.088 0.896-1.984 1.984-1.984s1.984 0.896 1.984 1.984c0 1.12-0.864 1.984-1.984 1.984zM19.648 27.808h-7.232c-0.576 0-1.024 0.48-1.024 1.056v0.096c0 0.576 0.448 1.056 1.024 1.056h7.2c0.576 0 1.056-0.48 1.056-1.056v-0.096c0-0.576-0.48-1.056-1.024-1.056z" fill="rgba(73,124,255,1)"></path>
                </g>
              </svg>
            </div>
            <div class="aichatContent">
              <div class="markdown-box-compile" v-html="item.aichatContent"></div>
              <p v-if="ifShowAiLoading && index == AIchatData.length-1" style="text-align: center;">思考中{{ aiThinkIcon }}</p>
            </div>
          </div>
          <div class="userArea" v-if="item.type == 'user'">
            <div class="chatContent">
              {{ item.content }}
            </div>
            <div class="iconArea">
              <svg class="userAvatarIcon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 32 32" width="40" height="40" style="" filter="none">
                <defs><linearGradient id="U9Gom8ZOUXvZzoGd9qaUV91" x1="0" x2="100%" y1="0" y2="0" gradientTransform="matrix(0.9859999999999999, 0.009000000000000008, -0.009000000000000008, 0.9859999999999999, 0.352, 16.064)" gradientUnits="userSpaceOnUse"><stop stop-color="#187eff" stop-opacity="1" offset="0"></stop><stop stop-color="#1742ff" stop-opacity="1" offset="1"></stop></linearGradient></defs>
                <g>
                <path d="M16 2.667c7.36 0 13.333 5.973 13.333 13.333s-5.973 13.333-13.333 13.333-13.333-5.973-13.333-13.333 5.973-13.333 13.333-13.333zM8.031 20.555c1.957 2.92 4.896 4.779 8.183 4.779 3.285 0 6.225-1.857 8.181-4.779-2.131-1.996-5.005-3.221-8.165-3.221-0.006 0-0.012 0-0.018 0h0.001c-0.005 0-0.012 0-0.018 0-3.16 0-6.033 1.226-8.171 3.227l0.007-0.006zM16 14.667c2.209 0 4-1.791 4-4s-1.791-4-4-4v0c-2.209 0-4 1.791-4 4s1.791 4 4 4v0z" fill="url(#U9Gom8ZOUXvZzoGd9qaUV91)"></path>
                </g>
              </svg>
            </div>
          </div>
        </div>
      </div>

      <div class="submitArea">
        <div class="bottomTextareaOut">
          <textarea class="bottomTextarea" v-model="inputBoxContent" ref="bottomTextarea" @input="getTextareaHeightHandler" @focus.stop="chatContentAreaScrollBottomHandler"></textarea>
        </div>
        <div class="submitBtnArea">
          <svg class="submitBtnIcon" @click="submitHandler" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 48 48" width="24" height="24" style="" filter="none">
            <g>
            <path d="M48 0H0V48H48V0Z" fill="rgba(4,70,253,0.84)" fill-opacity="0.01" stroke="none"></path><path d="M43 5L29.7 43L22.1 25.9L5 18.3L43 5Z" stroke="rgba(4,70,253,0.84)" stroke-width="4" stroke-linejoin="round" fill="none"></path><path d="M43.0001 5L22.1001 25.9" stroke="rgba(4,70,253,0.84)" stroke-width="4" stroke-linecap="round" stroke-linejoin="round" fill="none"></path>
            </g>
          </svg>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { store } from 'xijs';
import { getUserId } from '@/config/config.js'
import { aiRecordChatByRag } from '@/api/ai/index.js'
import { aiRecordChat } from '@/api/ai/index.js'
import { pageConstant } from '@/config/contant.js'
import { marked } from 'marked'
import 'highlight.js/styles/monokai-sublime.css'
marked.setOptions({
  renderer: new marked.Renderer(),
  highlight: function (code, lang) {
    const hljs = require('highlight.js')
    const language = hljs.getLanguage(lang) ? lang : 'plaintext'
    return hljs.highlight(code, { language }).value
  },
  langPrefix: 'hljs language-',
  breaks: false,
  gfm: true,
  headerIds: true,
  headerPrefix: '',
  mangle: true,
  pedantic: false,
  sanitize: false,
  silent: false,
  smartLists: false,
  smartypants: false,
  xhtml: false
})


const initAIchatData = [
  {
    type: 'AI',
    content: '您好！我是数字商铺AI助手，商铺相关问题都可以问我。'
  }
]
const AIchatData = ref([])
AIchatData.value = initAIchatData.map(item => {
  if (item.type == 'AI') {
    item.aichatContent = marked.parse(item.content)
  }

  return item
})

const bottomTextarea = ref(null)
const inputBoxContent = ref('')
const getTextareaHeightHandler = (e) => {
  if (bottomTextarea.value) {
    // 删除文本内容时，调整高度
    bottomTextarea.value.style.height = 19 + 'px'

    if (e.target.scrollHeight > 90) {
      bottomTextarea.value.style.height = 90 + 'px'
    } else {
      bottomTextarea.value.style.height = e.target.scrollHeight + 'px'
    }

    // inputBoxContent.value = e.target.value
  }
}
const chatContentArea = ref(null)
const chatContentAreaScrollBottomHandler = () => {
  setTimeout(() => {
    if (chatContentArea.value) {
      chatContentArea.value.scrollTop = chatContentArea.value.scrollHeight
    }
  }, 100)
}
const chatContentAreaTouchStartHandler = () => {
  if (bottomTextarea.value) {
    setTimeout(() => {
      bottomTextarea.value.blur()
    }, 100)
  }
}

const ifShowAiLoading = ref(false)
const aiThinkIcon = ref('......')
const lineByLineShowResponseTextHandler = async (responseText) => {
  let lineByLineShowArray = responseText.split(/(?<=\n)/)

  // 逐行显示
  let compileContent = ''
  for (let i = 0; i < lineByLineShowArray.length; i++) {
    await new Promise((resolve) => {
      setTimeout(resolve, 100)
        
    })
    ifShowAiLoading.value = false

    compileContent = compileContent + lineByLineShowArray[i]
    AIchatData.value[AIchatData.value.length -1].aichatContent = marked.parse(compileContent)
    chatContentAreaScrollBottomHandler()
  }
}

const submitHandler = () => {
  AIchatData.value.push({
    type: 'user',
    content: inputBoxContent.value
  })
  // 发起请求
  let params = {
    questionText: inputBoxContent.value
  }
  if (store.get(pageConstant.storageSyncUserKey).status == 0) {
    params['createBy'] = getUserId()
  }

  inputBoxContent.value = ''

  AIchatData.value.push({
    type: 'AI',
    content: ''
  })
  chatContentAreaScrollBottomHandler()

  const aiThinkIconInterval = setInterval(function() {
    if (aiThinkIcon.value.length == 6) {
      aiThinkIcon.value = '.'
    } else if (aiThinkIcon.value.length == 1) {
      aiThinkIcon.value = '...'
    } else if (aiThinkIcon.value.length == 3) {
      aiThinkIcon.value = '......'
    }
  }, 500);
  ifShowAiLoading.value = true

  aiRecordChatByRag(params).then(res => {
    // 关闭加载中提示
    clearInterval(aiThinkIconInterval);
    ifShowAiLoading.value = false

    if (res.data.code == pageConstant.okCode) {
      lineByLineShowResponseTextHandler(res.data.data)
    } else {
      // showToast(res.data.msg);
      AIchatData.value[AIchatData.value.length -1].aichatContent = marked.parse('服务器繁忙，请稍后再试')
      chatContentAreaScrollBottomHandler()
    }
  })
  .catch((err) => {
    console.log(err)
    ifShowAiLoading.value = false
    AIchatData.value[AIchatData.value.length -1].aichatContent = marked.parse('服务器繁忙，请稍后再试')
    chatContentAreaScrollBottomHandler()
  })
}
</script>

<style lang="scss" scoped>
.out {
  height: 100dvh;
  width: 100vw;

  .pageOut {
    width: 100%;
    box-sizing: border-box;
    display: flex;
    flex-flow: column nowrap;
    height: calc(100dvh - 50px);

    .chatContentArea {
      overflow: auto;
      flex-grow: 1;
      padding: 15px 15px 0;

      .chatItemArea:first-child {
        .AIArea {
          .aichatContent {
            padding: 0 15px;
          }
        }
      }

      .AIArea {
        display: flex;
        padding-bottom: 20px;

        .chatContent {
          padding: 10px 15px;
          line-height: 23px;
          background-color: rgb(244, 247, 255);
          border-radius: 5px;
        }

        .aichatContent {
          padding: 0 15px 10px;
          line-height: 23px;
          background-color: rgb(244, 247, 255);
          border-radius: 5px;
        }


        .iconArea {
          height: 44px;
          display: flex;
          align-items: center;
          padding-right: 10px;
        }
      }

      .userArea {
        display: flex;
        justify-content: end;
        padding-bottom: 20px;

        .chatContent {
          padding: 10px 15px;
          line-height: 23px;
          background-color: rgb(11, 72, 234);
          // background-color: rgb(24, 126, 255);
          color: #fff;
          border-radius: 5px;
        }

        .iconArea {
          height: 44px;
          display: flex;
          align-items: center;
          padding-left: 10px;
        }
      }
    }

    .submitArea {
      width: 100%;
      padding: 10px 15px 10px; 
      background-color: rgb(247, 247, 247);
      border-top: 1px solid #e8e8e8;
      box-sizing: border-box;

      display: flex;
      align-items: end;

      .bottomTextareaOut {
        padding: 8px 0;
        background-color: #fff;
        border-radius: 5px;

        flex-grow: 1;
      }
      .bottomTextarea {
        padding: 0 10px;
        height: 19px;
        border: 0px solid transparent;
        font-size: 16px;
        outline: none;
        box-sizing: border-box;

        width: 100%;
      }

      .submitBtnArea {
        height: 34px;
        display: flex;
        align-items: center;
        padding-left: 10px;
      }
    }
  }
}

::v-deep(p) {
    display: block; 
    margin: 1em 0;
    line-height: 1.5;
}
::v-deep(ol) {
    display: block;
    margin: 1em 0;
    list-style-type: decimal;
}
::v-deep(li) {
    margin-left: 40px;
    margin-right: 10px;
    line-height: 1.5;
}
::v-deep(ul) {
    li {
        margin-left: 0;
        margin-right: 10px;
        line-height: 1.5;
    }
}
::v-deep(li::marker) {
    unicode-bidi: isolate;
    font-variant-numeric: tabular-nums;
    text-transform: none;
    text-indent: 0px !important;
    text-align: start !important;
    text-align-last: start !important;
}
::v-deep(strong) {
    font-weight: bold;
}
::v-deep(h3) {
    display: block;
    font-size: 1.17em;
    margin: 1em 0;
    font-weight: bold;
    unicode-bidi: isolate;
}
::v-deep(h4) {
    display: block;
    margin-block-start: 1.33em;
    margin-block-end: 1.33em;
    margin-inline-start: 0px;
    margin-inline-end: 0px;
    font-weight: bold;
    unicode-bidi: isolate;
}
::v-deep(code) {
    font-family: monospace;
    white-space: normal !important;
}
::v-deep(pre) {
    display: block;
    font-family: monospace;
    unicode-bidi: isolate;
    white-space: pre;
    margin: 1em 0px;
}
::v-deep(.hljs-meta) {
    display: block;
}
::v-deep(.hljs-tag) {
    display: block;
}
</style>